package sync

import kotlin.concurrent.thread

const val lock1 = "杯子"
const val lock2 = "笔"
const val lock3 = "笔记本"

/*
死锁的演示
 */
fun main() {
   thread { 1.work() }
   thread { 2.work() }
   thread { 3.work() }
}

private fun Int.work() {
    when (this) {
        1 -> {
            1.something(lock1) {
                1.something(lock2) {
                    1.something(lock3)
                }
            }
        }
        2 -> {
            2.something(lock1) {
                2.something(lock2) {
                    2.something(lock3)
                }
            }
        }
        else -> {
            3.something(lock1) {
                3.something(lock2) {
                    3.something(lock3)
                }
            }
        }
    }
}

private fun Int.something(work: String, block: (() -> Unit)? = null) {
    synchronized(work) {
        println("$this : 拿到了 $work")
        Thread.sleep(10)
        block?.invoke()
    }
}